//
//  XCMineViewController.m
//  XCBabyBook
//
//  Created by hankeyboard on 2018/12/23.
//  Copyright © 2018 hankeyboard. All rights reserved.
//

#import "XCMineViewController.h"
#import "zhinanCell.h"
#import "GuanYuWoMenVC.h"
#import "XCFeedbackViewController.h"

@interface XCMineViewController ()<UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate>

@property (strong, nonatomic)UITableView *tableView;
@property (strong, nonatomic)NSArray *dataArr;
@property (strong, nonatomic)UIView *headerView;
@property (nonatomic, strong) UIImageView *headerImgView;
@property (nonatomic, strong) UILabel *nameLb;

@end

@implementation XCMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"个人中心";
    [self createUI];
}

- (void)createUI
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view);
        }
        make.left.right.mas_equalTo(self.view);
    }];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
    [self.view addSubview:_tableView];
    _dataArr = @[@[@"关于我们",@"意见反馈"],@[@"客服电话"]];
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.scrollEnabled = NO;
    self.tableView.tableHeaderView = [self headerView];
}

- (void)nameLbClick:(UITapGestureRecognizer *)tap {
    UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:@"设置用户名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertCtl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入用户名";
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alertCtl.textFields.firstObject;
        self.nameLb.text = textField.text;
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:self.nameLb.text forKey:@"userName"];
        [userDefaults synchronize];
    }];
    [alertCtl addAction:cancelAction];
    [alertCtl addAction:sureAction];
    [self presentViewController:alertCtl animated:YES completion:nil];
}
//2.实现相应代理事件,代理UIActionSheetDelegate,方法如下

- (void)headerImgViewClick:(UITapGestureRecognizer *)tap {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:                               @"设置头像" delegate:self cancelButtonTitle:@"取消"                       destructiveButtonTitle:nil otherButtonTitles:@"选择本地图片",@"拍照", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:                                                       (NSInteger)buttonIndex {
    // 相册 0 拍照 1
    switch (buttonIndex) {
        case 0:
            //从相册中读取
            [self readImageFromAlbum];
            break;
        case 1:
            //拍照
            [self readImageFromCamera];
            break;
            
        default:
            
            break;
    }
}

//3.实现从相册读取图片功能,代码如下
//从相册中读取

- (void)readImageFromAlbum {
    
    //创建对象
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    //（选择类型）表示仅仅从相册中选取照片
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    //指定代理，因此我们要实现UIImagePickerControllerDelegate,                                                 UINavigationControllerDelegate协议
    
    imagePicker.delegate = self;
    
    //设置在相册选完照片后，是否跳到编辑模式进行图片剪裁。(允许用户编辑)
    
    imagePicker.allowsEditing = YES;
    
    //显示相册
    
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}



//4.实现拍照功能



- (void)readImageFromCamera {
    
    if ([UIImagePickerController isSourceTypeAvailable:                                           UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];         imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;         imagePicker.delegate = self;
        
        imagePicker.allowsEditing = YES;
        
        //允许用户编辑
        
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    } else {
        //弹出窗口响应点击事件
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告"                         message:@"未检测到摄像头" delegate:nil cancelButtonTitle:nil                                                 otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }
    
}



//5.图片完成处理后提交,代理方法UIPickerControllerDelegate



//图片完成之后处理

- (void)imagePickerController:(UIImagePickerController *)picker        didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
    //image 就是修改后的照片
    
    //将图片添加到对应的视图上
    
    [_headerImgView setImage:image];
    NSData *data;
    
    /* 判断图片是不是png格式的文件 */
    if (UIImagePNGRepresentation(image))
    {
        /* 返回为png图像 */
        data = UIImagePNGRepresentation(image);
    }
    else
    {
        /* 返回为JPEG图像 */
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    
    /* 保存 */
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:data forKey:@"userIcon"];
    [userDefaults synchronize];
    
    //结束操作
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - UITableViewDeleagte
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataArr[section];
    return [arr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    zhinanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"zhinanCell"];
    if (!cell) {
        cell = [[[NSBundle bundleForClass:[self class]]loadNibNamed:@"zhinanCell" owner:self options:nil] firstObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *arr = _dataArr[indexPath.section];
    cell.label1.text = arr[indexPath.row];
    cell.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
    
    return cell;
}

#pragma mark -cell 点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    //行被选中后，自动变回反选状态的方法
    //    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            GuanYuWoMenVC * guanyuwomen = [[GuanYuWoMenVC alloc] init];
            guanyuwomen.panduanStr = @"guanyu";
            [self.navigationController pushViewController:guanyuwomen animated:YES];
        }
        if (indexPath.row == 1){
            XCFeedbackViewController * bangzhu = [[XCFeedbackViewController alloc] init];
            [self.navigationController pushViewController:bangzhu animated:YES];
        }
    } 
    
    if (indexPath.section == 1){
        [self openScheme:@"tel://4006781693"];
        
    }
}

- (void)openScheme:(NSString *)scheme {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *URL = [NSURL URLWithString:scheme];
    
    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
        [application openURL:URL options:@{}
           completionHandler:^(BOOL success) {
               NSLog(@"Open %@: %d",scheme,success);
           }];
    } else {
        BOOL success = [application openURL:URL];
        NSLog(@"Open %@: %d",scheme,success);
    }
}

- (UIView *)headerView {
    if (_headerView == nil) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kFitScreen(150))];
        _headerView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
        [self headerImgView];
        [self nameLb];
    }
    return _headerView;
}

- (UIImageView *)headerImgView {
    if (_headerImgView == nil) {
        _headerImgView = [UIImageView new];
        [self.headerView addSubview:_headerImgView];
        [_headerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(kFitScreen(80), kFitScreen(80)));
            make.centerX.mas_equalTo(self.headerView);
            make.top.mas_equalTo(self.headerView).offset(10);
        }];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [userDefaults objectForKey:@"userIcon"];
        if (data) {
            _headerImgView.image = [UIImage imageWithData:data];
        } else {
            _headerImgView.image = [UIImage imageNamed:@"userIcon"];
        }
        _headerImgView.layer.cornerRadius = kFitScreen(50) / 2.0;
        _headerImgView.layer.masksToBounds = YES;
        _headerImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerImgViewClick:)];
        [_headerImgView addGestureRecognizer:tap];
    }
    return _headerImgView;
}

- (UILabel *)nameLb {
    if (_nameLb == nil) {
        _nameLb = [UILabel new];
        [_headerView addSubview:_nameLb];
        [_nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.headerView);
            make.top.mas_equalTo(self.headerImgView.mas_bottom).offset(10);
        }];
        _nameLb.textColor = UIColorGray5;
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *name = [userDefaults objectForKey:@"userName"];
        if (name) {
            _nameLb.text = name;
        } else {
            _nameLb.text = @"未命名";
        }
        _nameLb.textAlignment = NSTextAlignmentCenter;
        _nameLb.font = UIFontMake(13);
        _nameLb.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nameLbClick:)];
        [_nameLb addGestureRecognizer:tap];
    }
    return _nameLb;
}

@end
